package com.ruoyi.merchant.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.merchant.annotation.DictFilter;
import com.ruoyi.merchant.dto.BaseDeviceInfoDto;
import com.ruoyi.merchant.vo.BaseDeviceInfoVo;
import com.ruoyi.merchant.vo.CustomerBaseVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.merchant.domain.BaseDeviceInfo;
import com.ruoyi.merchant.service.IBaseDeviceInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 设备信息Controller
 * 
 * @author chengxin.ju
 * @date 2023-12-12
 */
@RestController
@RequestMapping("/baseDeviceInfo")
public class BaseDeviceInfoController extends BaseController
{
    @Autowired
    private IBaseDeviceInfoService baseDeviceInfoService;

    /**
     * 查询设备信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BaseDeviceInfo baseDeviceInfo)
    {
        startPage();
        List<BaseDeviceInfo> list = baseDeviceInfoService.selectBaseDeviceInfoList(baseDeviceInfo);
        return getDataTable(list);
    }

    /**
     * 查询设备信息列表
     */
    @GetMapping("/list/v2")
    @DictFilter(dataType = "page")
    public TableDataInfo listV2(BaseDeviceInfo baseDeviceInfo)
    {
        startPage();
        //查询未删除的设备
        baseDeviceInfo.setDel(0L);
        baseDeviceInfo.setStatus(0L);
        List<BaseDeviceInfoVo> list = baseDeviceInfoService.selectBaseDeviceInfoListV2(baseDeviceInfo);
        return getDataTable(list);
    }

    /**
     * 导出设备信息列表
     */
    @Log(title = "设备信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BaseDeviceInfo baseDeviceInfo)
    {
        List<BaseDeviceInfo> list = baseDeviceInfoService.selectBaseDeviceInfoList(baseDeviceInfo);
        ExcelUtil<BaseDeviceInfo> util = new ExcelUtil<BaseDeviceInfo>(BaseDeviceInfo.class);
        util.exportExcel(response, list, "设备信息数据");
    }


    /**
     *  检查设备
     * @Author chengxin.ju
     * @Date  2020/3/25
     * @Param [employeeDto]
     * @return ju.maiya.huo.system.entities.base.BaseResultEntity
     **/
    @ResponseBody
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    public AjaxResult check(@RequestParam("imie") String imie) {
        try{

            BaseDeviceInfoDto baseDeviceInfoDto = new BaseDeviceInfoDto();
            baseDeviceInfoDto.setImie(imie);
            if(StringUtils.isEmpty(baseDeviceInfoDto.getImie())
                    || baseDeviceInfoDto.getImie().length() <15
                    || baseDeviceInfoDto.getImie().length() >17 ){
                return error("imie 需要符合 15-17 位的数");
            }
            List<BaseDeviceInfo> baseDeviceInfos = baseDeviceInfoService.selectBaseDeviceInfoList(baseDeviceInfoDto);

            if (CollectionUtils.isNotEmpty(baseDeviceInfos)){
                return error(baseDeviceInfoDto.getImie() + "设备IMIE或者ID号已存在。");
            }

            long count = baseDeviceInfos.stream().filter(item -> StringUtils.isNoneBlank(item.getCustomerId())
                    || StringUtils.isNoneBlank(item.getAppUserId())).count();
            if (count > 0 ){
                return error(baseDeviceInfoDto.getImie() + "设备IMIE或者ID号已已绑定，请先解绑！");
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return error("检查设备失败");
        }
        return success();
    }

    /**
     * 获取设备信息详细信息
     */
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfo(@RequestParam("id") String id)
    {
        return success(baseDeviceInfoService.selectBaseDeviceInfoById(id));
    }

    /**
     * 新增设备信息
     */
    @Log(title = "设备信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BaseDeviceInfo baseDeviceInfo)
    {
        return success(baseDeviceInfoService.insertBaseDeviceInfo(baseDeviceInfo));
    }

    /**
     * 修改设备信息
     */
    @Log(title = "设备信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map map) throws Exception {
        String toJSONString = JSONObject.toJSONString(map);
        BaseDeviceInfoDto baseDeviceInfoDto = JSONObject.parseObject(toJSONString,BaseDeviceInfoDto.class);
        if (StringUtils.isBlank(baseDeviceInfoDto.getId())){
            return error("设备id未传【id】！");
        }
        //发送指令
        if (baseDeviceInfoDto.getModel() == null){
            return error("model 参数未传");
        }
        return success(baseDeviceInfoService.updateBaseDeviceInfo(baseDeviceInfoDto));
    }

    /**
     *  设备和客户绑定 以蓝牙方式连接的mac唯一键
     * @Author chengxin.ju
     **/
    @ResponseBody
    @RequestMapping(value = "/execBinding", method = RequestMethod.POST)
    public AjaxResult execBinding(@RequestBody BaseDeviceInfo baseDeviceInfo) {
        if (StringUtils.isEmpty(baseDeviceInfo.getMac()) &&  StringUtils.isEmpty(baseDeviceInfo.getImie())){
            return error("设备mac地址或者设备标识码为空！");
        }
        if (StringUtils.isEmpty(baseDeviceInfo.getOrganId())){
            return error("请选择设备所属的机构！");
        }
        if (StringUtils.isEmpty(baseDeviceInfo.getCustomerId())){
            return error("请选择家人！");
        }

        return baseDeviceInfoService.execBinding(baseDeviceInfo);
    }

    /**
     *  设备和客户解绑
     * @Author chengxin.ju
     **/
    @ResponseBody
    @RequestMapping(value = "/execUnbind", method = RequestMethod.POST)
    public AjaxResult execUnbind(@RequestBody BaseDeviceInfo baseDeviceInfo) {
        return toAjax(baseDeviceInfoService.execUnbind(baseDeviceInfo));
    }


    /**
     * 删除设备信息
     */
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("id") String id) throws Exception {
        BaseDeviceInfoDto baseDeviceInfo = new BaseDeviceInfoDto();
        baseDeviceInfo.setId(id);
        //删除标志置位 1 即删除
        baseDeviceInfo.setDel(1L);
        baseDeviceInfoService.updateBaseDeviceInfo(baseDeviceInfo);
        return success();
    }


}
